package com.linjiahao.nettyBus.channel;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName GlobalChannel
 * @Description: TODO
 * @Author linjiahao
 * @Date 2023/1/9
 **/
@Component
@Slf4j
public class GlobalChannel {
    private final ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>(100);

    public void bindChannel(String userId,Channel channel){
        AttributeKey<String> key = AttributeKey.valueOf("userId");
        channel.attr(key).set(userId);
        this.channelMap.put(userId, channel);
        log.info("{}用户绑定通道{}成功",userId,channel.id());
    }

    public Channel getChannelByUserId(String userId) {
        return this.channelMap.get(userId);
    }

    public boolean removeChannel(String userId){
        if(channelMap.contains(userId)){
            channelMap.remove(userId);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public AttributeKey<String> getTokenKey(){
        AttributeKey<String> auth = AttributeKey.valueOf("userId");
        return auth;
    }

}
